package com.java.project.project.fulu.controller;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.java.common.utils.tool.Md5Utils;
import com.java.common.utils.tool.StringUtils;
import com.java.project.project.fulu.domain.Product;
import com.java.project.project.fulu.service.IProductService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.java.framework.aspectj.lang.annotation.Log;
import com.java.framework.aspectj.lang.enums.BusinessType;
import com.java.framework.web.controller.BaseController;
import com.java.framework.web.domain.AjaxResult;
import com.java.common.utils.poi.ExcelUtil;
import com.java.framework.web.page.TableDataInfo;

/**
 * 商品信息Controller
 * 
 * @author admin_dza
 * @date 2021-07-27
 */
@Controller
@RequestMapping("/fulu/product")
public class ProductController extends BaseController
{
    private String prefix = "fulu/product";
    @Value("${fulu.app_key}")
    public String appKey;
    @Value("${fulu.app_secret}")
    public String appSecret;
    @Value("${fulu.url}")
    public String url;

    @Autowired
    private IProductService productService;

    Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @RequiresPermissions("fulu:product:view")
    @GetMapping()
    public String product()
    {
        return prefix + "/product";
    }

    /**
     * 查询商品信息列表
     */
    @RequiresPermissions("fulu:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出商品信息列表
     */
    @RequiresPermissions("fulu:product:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Product product)
    {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        return util.exportExcel(list, "product");
    }

    /**
     * 新增商品信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        return prefix + "/add";
    }

    /**
     * 新增保存商品信息
     */
    @RequiresPermissions("fulu:product:add")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Product product)
    {
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改商品信息
     */
    @GetMapping("/edit/{details}")
    public String edit(@PathVariable("details") String details, ModelMap mmap)
    {
        Product product = productService.selectProductById(details);
        mmap.put("product", product);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品信息
     */
    @RequiresPermissions("fulu:product:edit")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Product product)
    {
        return toAjax(productService.updateProduct(product));
    }

    /**
     * 删除商品信息
     */
    @RequiresPermissions("fulu:product:remove")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(productService.deleteProductByIds(ids));
    }

    /**
     * 查询商品信息列表
     */

    @PostMapping("/syncProductInfo")
    @ResponseBody
    public AjaxResult syncProductInfo()
    {
        JSONObject req = new JSONObject();
        req.put("app_key",appKey);
        req.put("method","fulu.goods.list.get");
        req.put("timestamp",format.format(new Date()));
        req.put("version","2.0");
        req.put("format","json");
        req.put("charset","utf-8");
        req.put("sign_type","md5");
        req.put("app_auth_token","");
        req.put("biz_content","{}");
        String sign = Sign(appSecret,req);
        req.put("sign",sign);
//        System.out.println("request:"+req.toJSONString());
        String respon = HttpUtil.post(url, req.toJSONString());
//        System.out.println("respon:"+respon);
        JSONObject result = JSONObject.parseObject(respon);
        if (Integer.parseInt(result.get("code").toString())==0){
            String infoListStr = result.getString("result");
            List<Product> products = JSONArray.parseArray(infoListStr, Product.class);
            if (StringUtils.isNotEmpty(products)){
                if (productService.syncProductList(products)>0){
                    return AjaxResult.success("同步成功");
                }else {
                    return AjaxResult.error("同步失败");
                }
            }else {
                return AjaxResult.error("商品为空");
            }
        }else {
            return AjaxResult.error(result.getString("message"));
        }

    }

    public String Sign(String sysSecret,JSONObject map){

        char[] s = JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue).toCharArray();
        Arrays.sort(s);

        String outputSignOriginalStr = new String(s) + sysSecret;
        String sign = Md5Utils.MD5(outputSignOriginalStr);
        return sign;
    }
}
